#!/usr/bin/python
# -*- coding: utf-8 -*-


import  commands
import  nmap
import  csv
import  os
import  datetime
from    reportsPortscan import *
from    conf import varas

def autoscan():

    """
    Função que efectua o nmap e PortScan e envia os dados para o relatório
    """
    now = datetime.datetime.now()
    nm = nmap.PortScanner()
    if varas.IP == None:      
        a = commands.getoutput("/sbin/ifconfig").split("\n")[1].split()[1][5:]
        # filtro para o range do ip 0.0.0.*
        for x in range(4):
            b = a[len(a)-x-1:len(a)-x]
            if b == '.':
                break
        varas.IP = a[:len(a)-x]+'*'
    pass

    if varas.Port != None:
        nm.scan(hosts = varas.IP, ports=varas.Port, arguments = '-sV -sS -O')
    else:
        nm.scan(hosts = varas.IP,arguments = '-sV -sS -O')
   
    for host in nm.all_hosts():

        if nm[host].state() == 'up':
            if varas.verbose:      
                print('----------------------------------------------------')
                print('Host : {0} {1}'.format(host, nm[host].hostname()))
                print('State : {0}'.format(nm[host].state()))
                try:
                    print('Sistema Operativo :{0} Versão:{1}'.format(nm[host]['osclass'][0]['vendor'],nm[host]['osclass'][0]['osgen']))
                except:
                    pass
            varas.Data.append(["{0}".format(host),"{0}".format(nm[host].state()),"","",""])
            try:
                varas.Data.append([
                                "",
                                "OS :",
                                "{0} {1}".format(nm[host]['osclass'][0]['vendor'],nm[host]['osclass'][0]['osgen']),
                                "", ""])
            except:
                pass
            for proto in nm[host].all_protocols():
                if proto == 'tcp' : 
                    if varas.verbose:
                        print('----------')
                        print('Protocol : %s' % proto)
                    lport = nm[host]['tcp'].keys()
                    lport.sort()
                    for port in lport:
                        if varas.verbose:
                            print 'port: {0} State: {1} - {2} - {3} {4}'.format(port, 
                                                                                nm[host]['tcp'][port]['state'],
                                                                                nm[host]['tcp'][port]['name'],
                                                                                nm[host]['tcp'][port]['product'],
                                                                                nm[host]['tcp'][port]['version'])
                        varas.Data.append(["",
                                        "{0}".format(nm[host]['tcp'][port]['state']),
                                        "{0}".format(port),
                                        "{0}".format(nm[host]['tcp'][port]['name']),
                                        "{0} {1}".format(nm[host]['tcp'][port]['product'],nm[host]['tcp'][port]['version'])
                                        ])  

    if varas.pdf:
        CreatePdf()

if __name__ == '__main__':
    varas()
